package com.sip.stream.utils.zfy.consumer;

import android.media.Image;
import android.media.ImageWriter;
import android.media.MediaFormat;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.Surface;

import androidx.annotation.RequiresApi;

import com.sip.stream.utils.zfy.GSMediaSampleData;
import com.sip.stream.utils.zfy.encoder.IGSVideoEncoder;

import java.nio.ByteBuffer;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;

public class IPCPlatformConsumer implements IGSPlatformConsumer {
    private static final String TAG = "IPCPlatformConsumer";

    private byte[] SPSdata;
    private AtomicBoolean addKeyFrameSuccess;
    private Handler backgroundHandler;
    private HandlerThread backgroundThread;
    private ImageWriter imageWriter;
    private boolean stopFlag;
    private MediaFormat vdieoFormat;
    private IGSMediaObserver<IGSVideoEncoderConsumer> videoEncoderConsumerObserver;
    private IGSVideoEncoderConsumer videoEncoderLisener;
    private BlockingDeque<ByteBuffer> waitDeque;
    private IGSMediaObserver<IGSWAVConsumer> wavConsumerObserver;

    static  boolean lambda$getBackgroundHandler$0(Message message) {
        return false;
    }

    @Override
    public void forceSwitchMuxer() {
    }

    @Override
    public void onAudioStream(byte[] bArr, long j) {
    }

    @Override
    public void start() {
    }

    public IPCPlatformConsumer() {
        this.waitDeque = new LinkedBlockingDeque(5);
        this.addKeyFrameSuccess = new AtomicBoolean(false);
        this.videoEncoderLisener = new IGSVideoEncoderConsumer() {
            @Override
            public void encodeVideoError(String str) {
            }

            @Override
            public void encodeVideoSuccess(GSMediaSampleData gSMediaSampleData) {
                IPCPlatformConsumer.this.encodeVideoSuccess(gSMediaSampleData);
            }

            @Override
            public void setOutputFormat(MediaFormat mediaFormat) {
                IPCPlatformConsumer.this.vdieoFormat = mediaFormat;
            }

            @Override
            public void addObserver(IGSMediaObserver<IGSVideoEncoderConsumer> iGSMediaObserver) {
                IPCPlatformConsumer.this.videoEncoderConsumerObserver = iGSMediaObserver;
            }
        };
    }

    public IPCPlatformConsumer(IGSVideoEncoder iGSVideoEncoder) {
        this.waitDeque = new LinkedBlockingDeque(5);
        this.addKeyFrameSuccess = new AtomicBoolean(false);
        IGSVideoEncoderConsumer iGSVideoEncoderConsumer = new IGSVideoEncoderConsumer() {
            @Override
            public void encodeVideoError(String str) {
            }

            @Override
            public void encodeVideoSuccess(GSMediaSampleData gSMediaSampleData) {
                IPCPlatformConsumer.this.encodeVideoSuccess(gSMediaSampleData);
            }

            @Override
            public void setOutputFormat(MediaFormat mediaFormat) {
                IPCPlatformConsumer.this.vdieoFormat = mediaFormat;
            }

            @Override
            public void addObserver(IGSMediaObserver<IGSVideoEncoderConsumer> iGSMediaObserver) {
                IPCPlatformConsumer.this.videoEncoderConsumerObserver = iGSMediaObserver;
            }
        };
        this.videoEncoderLisener = iGSVideoEncoderConsumer;
        iGSVideoEncoder.addLisener(iGSVideoEncoderConsumer);
    }

    private synchronized Handler getBackgroundHandler() {
        if (this.backgroundThread == null || this.backgroundHandler == null) {
            HandlerThread handlerThread = new HandlerThread("CameraBackground");
            this.backgroundThread = handlerThread;
            handlerThread.start();
            this.backgroundHandler = new Handler(this.backgroundThread.getLooper(), new Handler.Callback() {
                @Override
                public  boolean handleMessage(Message message) {
                    return IPCPlatformConsumer.lambda$getBackgroundHandler$0(message);
                }
            });
        }
        return this.backgroundHandler;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setUp(Surface surface) {
        ImageWriter newInstance = ImageWriter.newInstance(surface, 3);
        this.imageWriter = newInstance;
        newInstance.setOnImageReleasedListener(new ImageWriter.OnImageReleasedListener() {
            @Override
            public void onImageReleased(ImageWriter imageWriter) {
                Log.i(IPCPlatformConsumer.TAG, "onImageReleased");
                try {
                    ByteBuffer byteBuffer = (ByteBuffer) IPCPlatformConsumer.this.waitDeque.take();
                    Log.i(IPCPlatformConsumer.TAG, "sampleData take");
                    try {
                        Image dequeueInputImage = imageWriter.dequeueInputImage();
                        Log.i(IPCPlatformConsumer.TAG, "planes.length " + dequeueInputImage.getPlanes().length);
                        int remaining = byteBuffer.remaining();
                        if (dequeueInputImage.getPlanes().length > 0) {
                            ByteBuffer buffer = dequeueInputImage.getPlanes()[0].getBuffer();
                            buffer.clear();
                            buffer.put(byteBuffer);
                        }
                        dequeueInputImage.setTimestamp(remaining);
                        imageWriter.queueInputImage(dequeueInputImage);
                        Log.i(IPCPlatformConsumer.TAG, "imageWriter queueInputImage");
                    } catch (Exception unused) {
                    }
                } catch (InterruptedException e) {
                    Log.e(IPCPlatformConsumer.TAG, e.getMessage());
                }
            }
        }, getBackgroundHandler());
        Image dequeueInputImage = this.imageWriter.dequeueInputImage();
        dequeueInputImage.setTimestamp(0L);
        this.imageWriter.queueInputImage(dequeueInputImage);
    }

    public synchronized void encodeVideoSuccess(GSMediaSampleData gSMediaSampleData) {
        Log.i(TAG, "encodeVideoSuccess " + gSMediaSampleData.getBufferInfo().flags);
        if (gSMediaSampleData.getBufferInfo().flags == 1) {
            byte[] bArr = this.SPSdata;
            if (bArr != null) {
                ByteBuffer allocateDirect = ByteBuffer.allocateDirect(bArr.length);
                allocateDirect.put(this.SPSdata);
                allocateDirect.position(0);
                this.waitDeque.offer(allocateDirect);
            }
            gSMediaSampleData.getByteBuf().limit(gSMediaSampleData.getBufferInfo().size);
            this.addKeyFrameSuccess.set(this.waitDeque.offer(gSMediaSampleData.getByteBuf()));
        } else if (gSMediaSampleData.getBufferInfo().flags == 2) {
            ByteBuffer byteBuf = gSMediaSampleData.getByteBuf();
            int remaining = byteBuf.remaining();
            byte[] bArr2 = new byte[remaining];
            byteBuf.get(bArr2);
            byte[] bArr3 = new byte[remaining];
            this.SPSdata = bArr3;
            System.arraycopy(bArr2, 0, bArr3, 0, remaining);
        } else if (this.addKeyFrameSuccess.get()) {
        } else {
            gSMediaSampleData.getByteBuf().limit(gSMediaSampleData.getBufferInfo().size);
            this.waitDeque.offer(gSMediaSampleData.getByteBuf());
        }
    }

    @Override
    public void stop() {
        this.stopFlag = true;
        IGSMediaObserver<IGSVideoEncoderConsumer> iGSMediaObserver = this.videoEncoderConsumerObserver;
        if (iGSMediaObserver != null) {
            iGSMediaObserver.onStop(this.videoEncoderLisener);
            this.videoEncoderConsumerObserver = null;
        }
    }

    @Override
    public void setVideoEncoder(IGSVideoEncoder iGSVideoEncoder) {
        iGSVideoEncoder.addLisener(this.videoEncoderLisener);
        iGSVideoEncoder.startEncode();
    }

    @Override
    public void stopVideo() {
        IGSMediaObserver<IGSVideoEncoderConsumer> iGSMediaObserver = this.videoEncoderConsumerObserver;
        if (iGSMediaObserver != null) {
            iGSMediaObserver.onStop(this.videoEncoderLisener);
            this.videoEncoderConsumerObserver = null;
        }
    }

    @Override
    public void addObserver(IGSMediaObserver<IGSWAVConsumer> iGSMediaObserver) {
        this.wavConsumerObserver = iGSMediaObserver;
    }
}
